package com.dotandmedia.action;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.dotmedia.dboperations.UserDatabaseOperations;
import com.dotmedia.entities.User;
import com.opensymphony.xwork2.ActionSupport;

/**
 * This action class returns true or false based on whether a user ext id already exists in the database or not.
 * 
 * @author siddharthsaha
 * 
 */
public class UserExtIdExsistAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
	private static Logger logger = Logger.getLogger("UserExtIdExistAction");
	private String userExtId;

	protected Map session;
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	Map<String, Object> userExtIdExsistJSON;

	private static String USER_EXT_ID_EXSIST = "userExtIdExsist";

	@Override
	public void setServletResponse(HttpServletResponse resp) {
		this.response = resp;
	}

	@Override
	public void setServletRequest(HttpServletRequest req) {
		this.request = req;
	}

	@Override
	public void setSession(Map session) {
		this.session = session;
	}

	public String getUserExtId() {
		return userExtId;
	}

	public void setUserExtId(String userExtId) {
		this.userExtId = userExtId;
	}

	// Action method
	/**
	 * This method is the main action class. This method will find whether the user ext id already exist in the database or not. If it already exist
	 * then this method will return true else it will return false - All in Strings.
	 */
	public String userExtIdExist() {
		logger.info("IN UserExtIdExistAction");
		userExtIdExsistJSON = new LinkedHashMap<String, Object>();
		UserDatabaseOperations userDatabaseOperations = new UserDatabaseOperations();
		List<User> usersWithTheExtId = userDatabaseOperations.getUserEntitiesWithExtId(userExtId);
		boolean exists = false;
		for (int usersWithTheExtIdIndex = 0; usersWithTheExtIdIndex < usersWithTheExtId.size(); usersWithTheExtIdIndex++) {
			User currentUserEntity = usersWithTheExtId.get(usersWithTheExtIdIndex);
			if (currentUserEntity.getUserExtId().equals(userExtId)) {
				logger.info("Obtained a user with the same user ext id");
				exists = true;
				break;
			}
		}
		if (exists) {
			logger.info("A user with the ext id " + userExtId + "already exists");
			userExtIdExsistJSON.put(USER_EXT_ID_EXSIST, true);
		} else {
			logger.info("A user with the user ext id " + userExtId + "does not already exist in the database");
			userExtIdExsistJSON.put(USER_EXT_ID_EXSIST, false);
		}
		logger.info("OUT UserExtIdExistAction");
		return SUCCESS;
	}
}
